package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.server.event.model.DriverOnlineEvent;
import com.ybkj.daijia.server.event.model.DriverTimeEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverTimeService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class DriverOnlineEventListener implements ApplicationListener<DriverOnlineEvent> {

    private static final Logger logger = LoggerFactory.getLogger(DriverOnlineEventListener.class);


    @Autowired
    private CompanyService companyService;

    @Autowired
    private DriverTimeService driverTimeService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @Override
    @Async
    public void onApplicationEvent(DriverOnlineEvent event) {

        Driver driver = (Driver) event.getSource();

        logger.debug("driver : {} is online.", driver.getUsername());

        //列表模式需要
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "driverOnline");
        jsonObject.put("driverID", driver.getId());
        jsonObject.put("driverName", driver.getRealname());
        Company mainCompany = companyService.getMain();
        Company driverCompany = companyService.findOne(driver.getCompanyId());
        WebSocketSend.boardcastToArea(jsonObject, driverCompany.getCityName(), mainCompany.getId());

        //上班记录
        DriverTimeEvent driverTimeEvent = new DriverTimeEvent("online", driver);
        applicationEventMulticaster.multicastEvent(driverTimeEvent);

    }

}
